/**
 * 情感散点图组件
 * 
 * 作用：展示一段时间内的情感数据分布
 * 使用：在首页分析区域展示情感值的时间分布
 * 数据：接收包含time(时间)和value(情感值)属性的数组
 * 特点：使用散点图展示情感数据，根据情感值显示不同颜色
 */

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 定义属性
const props = defineProps<{
  data: Array<{
    id: number,
    time: string,
    value: number
  }>
}>()

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 创建图表实例
  chart = echarts.init(chartContainer.value)
  
  // 更新图表数据
  updateChart()
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return
  
  // 检查数据是否为空
  if (!props.data || props.data.length === 0) {
    chart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      series: []
    })
    return
  }
  
  // 清除可能存在的"暂无数据"标题
  chart.setOption({
    title: {
      text: ''
    }
  })
  
  // 准备数据
  const scatterData = props.data.map(item => {
    // 将时间转换为小时（0-24）
    let hour = 0
    if (item.time.includes(':')) {
      const parts = item.time.split(':')
      hour = parseInt(parts[0])
    }
    
    return [hour, item.value, item.id]
  })
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params: any) {
        const item = props.data.find(d => d.id === params.value[2])
        if (!item) return ''
        
        // 根据情感值确定情感类型
        let sentimentType = '中性'
        let color = '#909399'
        
        if (item.value > 0.3) {
          sentimentType = '正面'
          color = '#67C23A'
        } else if (item.value < -0.3) {
          sentimentType = '负面'
          color = '#F56C6C'
        }
        
        return `
          <div style="padding: 5px;">
            <div style="margin-bottom: 5px;">
              <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>
              <span style="font-weight:bold;">${item.time}</span>
            </div>
            <div>情感值: <span style="font-weight:bold;">${item.value.toFixed(2)}</span></div>
            <div>情感类型: <span style="color:${color};font-weight:bold;">${sentimentType}</span></div>
          </div>
        `
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '时间 (小时)',
      min: 0,
      max: 24,
      interval: 3,
      axisLine: {
        lineStyle: {
          color: '#eaeaea'
        }
      },
      axisLabel: {
        formatter: function(value: number) {
          return value.toFixed(0) + ':00'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#f0f0f0'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '情感值',
      min: -1,
      max: 1,
      interval: 0.5,
      axisLine: {
        lineStyle: {
          color: '#eaeaea'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#f0f0f0'
        }
      },
      axisLabel: {
        formatter: function(value: number) {
          return value.toFixed(1)
        }
      }
    },
    series: [
      {
        type: 'scatter',
        data: scatterData,
        symbolSize: 12,
        itemStyle: {
          color: function(params: any) {
            const value = params.value[1]
            if (value > 0.3) {
              return '#67C23A' // 正面情感 - 绿色
            } else if (value < -0.3) {
              return '#F56C6C' // 负面情感 - 红色
            } else {
              return '#909399' // 中性情感 - 灰色
            }
          },
          opacity: 0.7,
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      },
      {
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: [],
        markLine: {
          silent: true,
          lineStyle: {
            color: '#409EFF',
            type: 'dashed',
            opacity: 0.5
          },
          data: [
            {
              yAxis: 0.3,
              label: {
                formatter: '正面阈值',
                position: 'end'
              }
            },
            {
              yAxis: -0.3,
              label: {
                formatter: '负面阈值',
                position: 'end'
              }
            }
          ]
        },
        markArea: {
          silent: true,
          itemStyle: {
            opacity: 0.1
          },
          data: [
            [
              {
                yAxis: 0.3,
                itemStyle: { color: '#67C23A' }
              },
              {
                yAxis: 1
              }
            ],
            [
              {
                yAxis: -0.3,
                itemStyle: { color: '#F56C6C' }
              },
              {
                yAxis: -1
              }
            ]
          ]
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 监听数据变化，更新图表
watch(() => props.data, () => {
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
})

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="scatter-chart-wrapper">
    <h3 class="chart-title">情感时间分布</h3>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<style scoped>
.scatter-chart-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.chart-container {
  width: 100%;
  height: 280px;
}
</style> 